﻿using System;

namespace StardandPattern
{
    internal class Program
    {
        //第三步是调用
        private static void Main(string[] args)
        {
            Console.WriteLine("测试开始......");
            Stock stock = new Stock("公司中央仓库");
            stock.PriceChanged += Stock_PriceChanged;
            //设定价格
            Console.WriteLine("赋予新的价格");
            stock.Price = 100m;
        }

        private static void Stock_PriceChanged(object sender, PriceChangedEventArgs e)
        {
            Console.WriteLine($"价格修改了，旧的价格{e.oldPrice}是最新的价格是{e.newPrice}");
        }
    }

    //第一步是定义EventArgs
    public class PriceChangedEventArgs : EventArgs
    {
        public readonly decimal oldPrice;
        public readonly decimal newPrice;

        public PriceChangedEventArgs(decimal _oldPrice, decimal _newPrice)
        {
            this.oldPrice = _oldPrice;
            this.newPrice = _newPrice;
        }
    }

    //第二步是创建发布者

    public class Stock
    {
        private decimal price;
        private string symbol;

        public Stock(string symbol)
        {
            this.symbol = symbol;
        }

        public decimal Price
        {
            get { return price; }
            set
            {
                if (price == value) return;
                decimal oldPrice = price;
                price = value;
                OnPriceChanged(new PriceChangedEventArgs(oldPrice, price));
            }
        }

        //定义事件
        public event EventHandler<PriceChangedEventArgs> PriceChanged;

        //我们可以修改此事件
        public virtual void OnPriceChanged(PriceChangedEventArgs priceChangedEventArgs)
        {
            PriceChanged?.Invoke(this, priceChangedEventArgs);
        }
    }
}